package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.domain.Employee;
import cn.ztr.ymcc.domain.Login;
import cn.ztr.ymcc.domain.LoginRole;
import cn.ztr.ymcc.domain.Role;
import cn.ztr.ymcc.dto.LoginDTO;
import cn.ztr.ymcc.feign.EmployeeFeign;
import cn.ztr.ymcc.jwt.JwtUtils;
import cn.ztr.ymcc.jwt.PayLoadData;
import cn.ztr.ymcc.jwt.RsaUtils;
import cn.ztr.ymcc.mapper.LoginMapper;
import cn.ztr.ymcc.mapper.RoleMapper;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.ILoginService;
import cn.ztr.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Payload;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-02-24
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmployeeFeign employeeFeign;

    /**
     * 员工和用户登录
     * @param loginDTO
     * @return JsonResult
     */
    @Override
    public JsonResult login(LoginDTO loginDTO) {
        try {
            //1 检查是否存在该账号
            Login loginInfo = baseMapper.selectOne(new QueryWrapper<Login>()
                    .eq("username", loginDTO.getUsername())
                    .eq("type",loginDTO.getType()));
            AssertUtil.isNotNull(loginInfo,"账号不存在");
            //2 检查密码是否正确
            boolean matches = new BCryptPasswordEncoder().matches(loginDTO.getPassword(), loginInfo.getPassword());
            AssertUtil.isTrue(matches,"账号错误");
            //3 将当前账号信息保存到载荷中
            PayLoadData payLoadData = new PayLoadData();
            payLoadData.setLoginInfo(loginInfo);
            if (loginInfo.getType()==0){
                //4.1 账号为管理账号
                //4.1.1 查询管理员信息,放入载荷类
                /*JsonResult jsonResult = employeeFeign.getByLoginId(loginInfo.getId());
                String s = JSON.toJSON(jsonResult.getData()).toString();
                Employee employee = JSON.parseObject(s, Employee.class);
                payLoadData.setUser(employee);
                //4.1.2查询管理员权限放入载荷类
                //4.1.2.1 查询当前账号的角色信息
                List<Long> roleIdByLoginId = baseMapper.findRoleIdByLoginId(loginInfo.getId());
                //4.1.2.2 查询角色对应的权限
                List<String> permissionByRoleId = roleMapper.findPermissionByRoleId(roleIdByLoginId);
                payLoadData.setPermissions( permissionByRoleId);
                if (roleIdByLoginId!=null){
                    //4.1.2.2 根据角色信息查询权限

                }*/
                //4.1.3 查询管理员菜单放入载荷类
            }else {
                //4.2 账号为用户账号
                //4.1.1 查询用户信息,放入载荷
            }
            //5 获取token
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(payLoadData, privateKey, 720);
            //6 返回信息给前端
            Map<String,Object> map = new HashMap<>();
            map.put("jwtToken",token);
            map.put("loginInfo",loginInfo);
            return JsonResult.me(map);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 添加员工信息到login和loginRole表
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult addLogin(Login entity) {
        super.save(entity);
        LoginRole loginRole = new LoginRole();
        loginRole.setLoginId(entity.getId());
        loginRole.setRoleId(2l);
        baseMapper.addLoginRole(loginRole);
        return JsonResult.me(entity);

    }
}
